<template>
    <div v-if="team">
        <van-cell title="队伍名称" :value="team?.teamName" />
        <van-cell title="队伍描述" :value="team?.description" />
        <van-cell title="过期时间" :value="moment(team.expireTime).format('YYYY-MM-DD')" />
        <van-cell title="队伍最大人数" :value="team?.maxNum" />
        <van-cell title="建队时间" :value="moment(team.createTime).format('YYYY-MM-DD')" />
        <van-cell title="队长" :value="team.createUser.username" />
        <van-cell title="队伍人数" :value="team?.hasJoinNum" />
        <van-cell is-link title="队员信息" @click="show = true" />
    </div>
    <van-action-sheet v-model:show="show" :actions="actions" cancel-text="取消" description="队员信息"
        close-on-click-action />
    <div style="text-align: center; margin-top: 10px;" v-if="team">
        <van-button icon="plus" type="success" text="加入队伍" size="normal" round @click="joinTeam" v-if="!hasJoin" />
        <van-button icon="cross" type="danger" text="退出队伍" size="normal" round @click="exitTeam" v-else />
    </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";
import moment from 'moment'
import request from "@/utils/axios";
import { showFailToast, showSuccessToast } from "vant";
import router from "@/routes";
const route = useRoute();
const team = ref()
let show = ref(false)
let hasJoin = ref(false)
const actions = ref([])
onMounted(async () => {
    const teamId = route.query.id
    const res = await request.get("team/getInfo", {
        params: {
            teamId,
        }
    })
    actions.value = res.data.userList.map((user, index) => {
        if (index === 0) {
            return {
                name: user.username,
                subname: '队长'
            }
        } else {
            return {
                name: user.username,
                subname: '队员'
            }
        }
    })
    if (res.code === 0) {
        team.value = res.data
    }
    hasJoin.value = team.value.hasJoin

})

const joinTeam = async() => {
    const res = await request.post('team/join',{
        teamId:route.query.id
    }) 
    if(res.code === 0){
        showSuccessToast('加入队伍成功！')
        router.push('/team')
    }else {
        showFailToast(`${res.message}`)
    }
    
}
const exitTeam = async() => {
    const res = await request.post('team/exit',{
        teamId:route.query.id
    }) 
    if(res.code === 0){
        showSuccessToast('退出队伍成功！')
        router.push('/team')
    }else {
        showFailToast(`${res.message}`)
    }
}
</script>

<style scoped></style>